package com.abu.edums.service.impl;

import com.abu.edums.listener.CategoryEventListener;
import com.abu.pojo.*;
import com.abu.edums.mapper.SubjectMapper;
import com.abu.vo.Category;
import com.abu.vo.CategoryVO;
import com.abu.edums.service.SubjectService;
import com.abu.exceptionhandler.EduException;
import com.abu.vo.SubjectVo;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author 阿布
 * @since 2020-06-17
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    @Autowired
    private SubjectMapper subjectMapper;

    @Override
    public void getFile(MultipartFile file) {
        if (file == null) {
            throw new EduException(20001, "文件不能为空");
        }
//            进行读取excel
        try {
            EasyExcel.read(file.getInputStream(), ExcelObject.class, new CategoryEventListener(this)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<CategoryVO> queryAllByPid(String id) {
//        通过一级分类查询所有的二级分类
        List<SubjectVo> subjectVoList = this.subjectMapper.selectByPid(id);
//        进行转换
        List<CategoryVO> categoryVoList = subjectVoList.stream().map(subjectVo -> {
//            赋值一级分类内容
            CategoryVO categoryVo = new CategoryVO();
            categoryVo.setId(subjectVo.getId());
            categoryVo.setTitle(subjectVo.getTitle());
//            赋值二级分类内容
            List<Category> list = subjectVo.getSubjectList().stream().map(subject -> {
                Category category = new Category();
                category.setId(subject.getId());
                category.setTitle(subject.getTitle());
                return category;
            }).collect(Collectors.toList());
            categoryVo.setChildren(list);
            return categoryVo;
        }).collect(Collectors.toList());
//        判断是否为空
        if (CollectionUtils.isEmpty(categoryVoList)) {
            return null;
        }
        return categoryVoList;
    }

}
